<?php

namespace app\common\model;

class Admin extends BaseModel
{
    protected $autoWriteTimestamp = 'datetime';

    protected $updateTime = false;

    /**
     * 关联订单
     * @return \think\model\relation\HasMany
     * @date 2021/01/26
     * @author longli
     */
    public function orders()
    {
        return $this->hasMany(Orders::class, "create_by", "id");
    }

    /**
     * 密码加密
     * @param $password
     * @return string
     */
    public static function encryptPassword($password)
    {
        return password_hash($password, PASSWORD_DEFAULT);
    }

    /**
     * 获取所有后台账号
     * @return array|\PDOStatement|string|\think\Collection
     * @date 2020/09/18
     * @author longli
     */
    public static function getAll()
    {
        return static::where("status", self::IS_YES)->order("username")->select();
    }

    /**
     * 通过用户id, 获取用户昵称
     * @param int $userId 用户id
     * @return string
     * @date 2021/01/22
     * @author longli
     */
    public static function getNicknameById($userId)
    {
        if(empty($userId) || !($user = static::get($userId))) return "";
        return $user->nickname;
    }

    /**
     * 通过用户id, 批量获取用户昵称
     * @param $userIds
     * @return array
     * @date 2021/04/02
     * @author longli
     */
    public static function getNicknameByIds($userIds)
    {
        $ret = [];
        foreach(static::field(['id', 'nickname'])->whereIn("id", $userIds)->select() as $item)
            $ret[$item->id] = $item->nickname;
        return $ret;
    }

    /**
     * 是否为超级管理员
     * @return bool
     * @date 2021/01/22
     * @author longli
     */
    public function isSuperAdmin()
    {
        return $this->id === 1;
    }

    /**
     * 判断是否有菜单权限
     * @param string|string[] $rule 规则id，或者规划路径，支持判断多个
     * @return bool
     * @date 2021/01/10
     * @author longli
     */
    public function hasPermissions($rule = '')
    {
        // 如果是超级管理员直接返回
        if($this->isSuperAdmin()) return true;
        try
        {
            $rs = AuthRule::field("id")
                ->where("id", "in", $rule)
                ->whereOr("name", "in", $rule)
                ->select();
            if($rs->isEmpty()) return false;
            $groups = \app\common\library\Rbac::instance()->getGroups($this->id);
            foreach($rs as $r)
            {
                $flag = true;
                foreach($groups as $group)
                {
                    $temp = explode(',', $group['rules']);
                    if(in_array($r->id, $temp))
                    {
                        $flag = false;
                        break;
                    }
                }
                if($flag) return false;
            }
            return true;
        }catch (\Exception $e){}
        return false;
    }
}
